﻿using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using WPF自由布局.ViewModels;

namespace WPF自由布局.Views
{
    public partial class DraggableDataGrid : UserControl
    {
        public DraggableDataGrid()
        {
            InitializeComponent();
        }

        // 注册 ItemsSource 依赖属性
        public static readonly DependencyProperty ItemsSourceProperty =
            DependencyProperty.Register("ItemsSource", typeof(ObservableCollection<SensorViewModel>), typeof(DraggableDataGrid),
                new PropertyMetadata(null, OnItemsSourceChanged));

        public ObservableCollection<SensorViewModel> ItemsSource
        {
            get => (ObservableCollection<SensorViewModel>)GetValue(ItemsSourceProperty);
            set => SetValue(ItemsSourceProperty, value);
        }

        private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var control = d as DraggableDataGrid;
            if (control == null) return;

            if (e.OldValue is ObservableCollection<SensorViewModel> oldCollection)
            {
                oldCollection.CollectionChanged -= control.OnItemsCollectionChanged;
            }
            if (e.NewValue is ObservableCollection<SensorViewModel> newCollection)
            {
                newCollection.CollectionChanged += control.OnItemsCollectionChanged;
            }
            control.UpdateDataGridColumns();
        }

        private void OnItemsCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            dataGrid.Items.Refresh();
        }

        // 更新 DataGrid 的列
        private void UpdateDataGridColumns()
        {
            dataGrid.AutoGenerateColumns = false;

            // 清除现有列并添加新的固定列
            dataGrid.Columns.Clear();
            dataGrid.Columns.Add(new DataGridTextColumn
            {
                Header = "传感器名称",
                Binding = new Binding("SensorName")
            });

            dataGrid.Columns.Add(new DataGridTextColumn
            {
                Header = "时间",
                Binding = new Binding("LatestDataPoint.Timestamp")
            });

            dataGrid.Columns.Add(new DataGridTextColumn
            {
                Header = "值",
                Binding = new Binding("LatestDataPoint.Value")
            });

            dataGrid.Columns.Add(new DataGridTextColumn
            {
                Header = "单位",
                Binding = new Binding("LatestDataPoint.Unit")
            });
        }
    }
}
